package com.css.dzj.dzjap.common.menu;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.css.aq.server.service.BaseService;
import com.css.dzj.dzjap.common.util.R;
import com.css.dzj.dzjap.common.util.ServiceUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.PropertySource;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/menu")
@PropertySource(value = "classpath:base.properties")
public class GetMenuController {
    @Autowired
    private BaseService baseService;
    @Autowired
    private HttpServletRequest request;
    @GetMapping("/getMenu")
    public R getMenu(){
        String  id= ServiceUtil.getUserId(request);
        Long userId=Long.parseLong(id.toString());
        Long appId=0L;
        List<Map<String,Object>> sysApp= ServiceUtil.getSysApp(request);
        for (Map<String,Object> app: sysApp) {
            if(app.get("appName").equals("安评系统")){
               appId=Long.parseLong(app.get("appId").toString());
            }
        }
        Map map=baseService.listMenuByUserIdAndAppId(userId,appId);
        //Map map= baseService.listMenuByUserId(userId);
       //String url = BASE_URL+BASE_API_MENU;

       // R data = serviceUtil.getInfoFromBase(url, null, true, false);
//        System.out.println(data.acquier("data"));
        String data=JSON.toJSONString(map);
        JSONObject menuData = (JSONObject) JSON.parse(data);
//        System.out.println(menuData.acquier("result"));
        JSONArray menuInfo = (JSONArray) menuData.get("result");
        //      System.out.println(menuInfo);

        JSONArray fastBtn = new JSONArray();
        addFastEntry(menuInfo, fastBtn);

        return R.ok().put("data", data).put("fastBtn",fastBtn);
    }

    public void addFastEntry(JSONArray mi, JSONArray fb){
        for (Object obj : mi) {
            JSONObject one = (JSONObject) obj;
            if(one.get("children") != null){
                JSONArray jsa = (JSONArray) one.get("children");
                addFastEntry(jsa, fb);
            }else{
//                System.out.println(one);
                JSONObject node = new JSONObject();
                node.put("id", one.get("id"));
                node.put("text", one.get("text"));
                node.put("url", one.get("url"));
                fb.add(node);
            }
        }
    }
}
